package com.deanlib.cabinet.ui.adapter;

import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.GeneratePresignedUrlRequest;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.deanlib.cabinet.R;
import com.deanlib.cabinet.data.AppDatabase;
import com.deanlib.cabinet.data.db.ResourceDao;
import com.deanlib.cabinet.data.model.Resource;
import com.deanlib.cabinet.utils.ConfigManager;
import com.deanlib.cabinet.utils.FileUtilsExt;
import com.deanlib.cabinet.utils.OssManager;
import com.deanlib.plantern.utils.FileUtils;
import com.deanlib.plantern.utils.FormatUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MediaGridAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public static final int VIEW_TYPE_ITEM_TIME    = 0;
    public static final int VIEW_TYPE_ITEM_CONTENT = 1;

    private List<MediaGridData> mDataList;

    public MediaGridAdapter(List<MediaGridData> dataList) {
        mDataList = dataList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == VIEW_TYPE_ITEM_TIME) {
            return new TitleHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_media_title_item, parent, false));
        } else {
            return new ContentHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_media_content_item, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (getItemViewType(position) == VIEW_TYPE_ITEM_TIME) {
            TitleHolder titleHolder = (TitleHolder) holder;
            titleHolder.tvTitle.setText(mDataList.get(position).getTitle());
        } else {
            Resource resource = mDataList.get(position).getData();
            if (resource!=null) {
                ContentHolder contentHolder = (ContentHolder) holder;
                String url = resource.localThumbnail;
                if (TextUtils.isEmpty(url)){
                    url = resource.localPath;
                }
                if (!TextUtils.isEmpty(url)) {
                    // url 模式
                    Glide.with(contentHolder.imgPhoto.getContext()).load(url)
                            .apply(RequestOptions.placeholderOf(R.drawable.placeholer).error(R.drawable.error))
                            .into(contentHolder.imgPhoto);
                }else {
                    contentHolder.imgPhoto.setImageResource(R.drawable.placeholer);
                    String objPath = resource.thumbnail;
                    if (TextUtils.isEmpty(objPath) && FileUtilsExt.isImage(resource.mineType)){
                        objPath = resource.path;
                    }
                    if (!TextUtils.isEmpty(objPath)) {
                        GetObjectRequest request = new GetObjectRequest(
                                ConfigManager.getInstance().getOssKey().extend2,
                                OssManager.createObjKey(resource.md5, objPath.substring(objPath.lastIndexOf("."))));
//                      String style = "image/resize,m_fixed,w_100,h_100/rotate,90";
                        String style = "image/resize,w_300"; //todo 可以按屏幕分辨率做调整
                        request.setxOssProcess(style);
                        OssManager.getInstance().getOssClient().asyncGetObject(request, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
                            @Override
                            public void onSuccess(GetObjectRequest request, GetObjectResult result) {
                                File outFile = new File(FileUtils.getDiskCachePath(), resource.md5+"_thumbnail");
                                if(FileUtilsExt.saveFileByStream(result.getObjectContent(), outFile.getPath())){
                                    Glide.with(contentHolder.imgPhoto.getContext()).load(outFile.getPath())
                                            .apply(RequestOptions.placeholderOf(R.drawable.placeholer).error(R.drawable.error))
//                                            .into(contentHolder.imgPhoto); //这种方式，不显示，需要滚动一下才能显示 ，不知为什么
                                            .into(new CustomTarget<Drawable>() {
                                                @Override
                                                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                                    contentHolder.imgPhoto.setImageDrawable(resource);
                                                }

                                                @Override
                                                public void onLoadCleared(@Nullable Drawable placeholder) {

                                                }

                                                @Override
                                                public void onLoadStarted(@Nullable Drawable placeholder) {
                                                    super.onLoadStarted(placeholder);
                                                    contentHolder.imgPhoto.setImageDrawable(placeholder);
                                                }

                                                @Override
                                                public void onLoadFailed(@Nullable Drawable errorDrawable) {
                                                    super.onLoadFailed(errorDrawable);
                                                    contentHolder.imgPhoto.setImageDrawable(errorDrawable);
                                                }
                                            });
//                                    contentHolder.imgPhoto.setImageResource(R.mipmap.ic_launcher);
                                }else {
                                    //todo
                                }
                            }

                            @Override
                            public void onFailure(GetObjectRequest request, ClientException clientException, ServiceException serviceException) {
                                //todo
                            }
                        });
                    }else {
                        // 视频没有封面图 todo
                    }
                }

                if (FileUtilsExt.isVideo(resource.mineType)) {
                    contentHolder.imgPlay.setVisibility(View.VISIBLE);
                    contentHolder.tvDuration.setVisibility(View.VISIBLE);
                    String duration = FormatUtils.convertTimestampToDuration(resource.duration*1000);
                    if (duration.startsWith("00:")) {
                        duration = duration.substring(3);
                    }
                    contentHolder.tvDuration.setText(duration);
                } else {
                    contentHolder.imgPlay.setVisibility(View.GONE);
                    contentHolder.tvDuration.setVisibility(View.GONE);
                }
                if (TextUtils.isEmpty(resource.path)) {
                    contentHolder.imgSyncState.setVisibility(View.VISIBLE);
                    contentHolder.imgSyncState.setOnClickListener(view -> {
                        //todo 加入上传队列，且优先级最高
                    });
                } else {
                    contentHolder.imgSyncState.setVisibility(View.GONE);
                }
            }
        }
    }

    @Override
    public int getItemCount() {
        return mDataList == null ? 0 : mDataList.size();
    }

    @Override
    public int getItemViewType(int position) {
        return mDataList.get(position).getType();
    }

    static class ContentHolder extends RecyclerView.ViewHolder {

        ImageView imgPhoto;
        ImageView imgPlay;
        ImageView imgSyncState;
        TextView tvDuration;

        ContentHolder(View itemView) {
            super(itemView);
            imgPhoto = itemView.findViewById(R.id.imgPhoto);
            imgPlay = itemView.findViewById(R.id.imgPlay);
            tvDuration = itemView.findViewById(R.id.tvDuration);
            imgSyncState = itemView.findViewById(R.id.imgSyncState);
        }
    }

    static class TitleHolder extends RecyclerView.ViewHolder {

        TextView tvTitle;

        TitleHolder(View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.tvTitle);
        }
    }

    public static class MediaGridData{
        private Resource data;
        private String title;
        private int type;

        public Resource getData() {
            return data;
        }

        public void setData(Resource data) {
            this.data = data;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }
    }

}
